package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.behavior.entity.ApReadBehavior;
import com.usian.behavior.mapper.ApReadBehaviorMapper;
import com.usian.behavior.service.IApReadBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.common.util.BeanHelper;
import com.usian.model.behavior.dtos.ReadBehaviorDto;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP阅读行为表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-10-14
 */
@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements IApReadBehaviorService {

    @Override
    public void saveReadBehavior(ReadBehaviorDto dto) {
        //1、参数校验
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2、判断用户是否登录
        Boolean isUser=false;
        //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId!=null) {
            isUser=true;
        }

        //3、查询用户或者设备是否对当前文章进行过阅读
        QueryWrapper<ApReadBehavior> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApReadBehavior::getArticleId,dto.getArticleId());
        if(isUser){
            //设置用户查询条件
            queryWrapper.lambda().eq(ApReadBehavior::getApUserId,userId);
        }else{
            //设置设备号查询条件
            queryWrapper.lambda().eq(ApReadBehavior::getEquipmentId,dto.getEquipmentId());
        }
        //执行查询
        ApReadBehavior readBehavior = this.getOne(queryWrapper);

        if(readBehavior==null){
            //4、如果没有阅读，记录阅读行为
            readBehavior = new ApReadBehavior();
            readBehavior.setCount(dto.getCount());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setPercentage(dto.getPercentage());
            if(isUser){
                readBehavior.setApUserId(userId);
            }else{
                readBehavior.setEquipmentId(dto.getEquipmentId());
            }
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setCreatedTime(new Date());
            boolean b = this.save(readBehavior);
            if (!b) {
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存阅读行为失败");
            }
        }else {
            //5、如果阅读过，阅读次数加一
            readBehavior.setCount(readBehavior.getCount()+dto.getCount());
            readBehavior.setUpdatedTime(new Date());
            boolean b = this.updateById(readBehavior);
            if (!b) {
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"修改阅读行为失败");
            }
        }

    }
}
